<?php

/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);
//header("Content-Type:text/html;charset=utf8");
use \GatewayWorker\Lib\Gateway;

require_once  "mysql-master/src/Connection.php";
//require_once  "Queueds.php";

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Events
{

    /**
     * 新建一个类的静态成员，用来保存数据库实例
     */
    private static $db = null;
    private static $queueds = null;

    /**
     * 进程启动后初始化数据库连接
     */
    public static function onWorkerStart($worker)
    {
        //self::$db = new \Workerman\MySQL\Connection('106.15.183.188', '3306', 'new_nydata', 'new_nydata', 'new_nydata');
        self::$db = new \Workerman\MySQL\Connection('localhost', '3306', 'new_nydata', 'new_nydata', 'new_nydata');
        //       self::$queueds =  new Queueds("first");
        var_dump("mysql connect successed");
        //       var_dump("duilie connect successed");
    }
    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     *
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {

        //        Gateway::sendToAll("$client_id login\r\n");
        var_dump("新的连接" . $client_id);
    }

    /**
     * 当客户端发来消息时触发
     * @param int $client_id 连接id
     * @param mixed $message 具体消息
     */
    public static function onMessage($client_id, $message)
    {

        $data1 = json_decode($message, true);

        var_dump("receive  message----");
        var_dump($data1);
		
        //接收上传数据
        //        $con = mysqli_connect('localhost','root','root','new_nydata');
        $sql1 = "insert into ny_linshi_data(`time`,`data`) values('" . date("Y-m-d H:i:s", time()) . "','" . json_encode($message) . "')";
        self::$db->query($sql1);
        // web端命令
        if ($_SERVER['GATEWAY_PORT'] == 65510) {

            if ($data1['type']  &&  $data1['type'] == 'ping') {
            	
            } else {
                $uid = Gateway::getUidByClientId($client_id);

                if (!$uid) {
                    Gateway::bindUid($client_id, $data1['uid']);
                    var_dump('bind_web');
                }


                // 发送命令到web和手机端
                //            Gateway::sendToUid($data1['uid'],json_encode(['type'=>'reload']));

                // 操作数据库
                //            $db = new \Workerman\MySQL\Connection('localhost', '3306', 'root', 'root', 'new_nydata');
                $sql = "update  nyd_dev  set is_open = '" . $data1['data']['data'] . "' where dev_mac = '" . $data1['data']['dev_id'] . "'";
//                var_dump($sql);
                $re = self::$db->query($sql);
                if ($re !== false) {
                    //  发送命令到web和手机端
                    Gateway::sendToUid($data1['uid'], 'success');
                    // 发送命令道指定大棚
                    Gateway::sendToUid($data1['gateway_id'], json_encode($data1['data']));
                } else {
                    //  发送命令到web和手机端
                    Gateway::sendToUid($data1['uid'], 'error');
                }
            }
        } // 大棚数据
        elseif ($_SERVER['GATEWAY_PORT'] == 65520) {
			$data1["time"]=time();
            // 绑定网关id
            $uid = Gateway::getUidByClientId($client_id);
            if (!$uid) {
                Gateway::bindUid($client_id, $data1['gateway_id']);
                var_dump('bind_dapeng');
            }
            $Redis = new Redis();
            $Redis->connect('127.0.0.1', 6379);

            // type == 5 说明是设备状态上传(断开 接入)
            if ($data1['type'] == 5) {
                  $status = $Redis->get($data1['gateway_id']."_status");
				    $status_1 =[];
					  foreach($data1['data'] as $k =>$v){
						if($v['mac_id'] == "led_1"){
							$status_1['led_1'] = $v['data'];
						}
						if($v['mac_id'] == "zengy"){
							$status_1['zengy'] = $v['data'];
						}
						if($v['mac_id'] == "fengs"){
							$status_1['fengs'] = $v['data'];
						}
					  }
				  if(!$status){
						//$queueds = new Queueds("first");
                        //$queueds->send($data1);
				
				  }else{
					 $res =  array_diff(json_decode($status,true),$status_1);
					 if($res){
						  //$queueds = new Queueds("first");
						  //$queueds->send($data1);
					 }
				  }
				   $Redis->set($data1['gateway_id']."_status",json_encode($status_1));
					  
//                $res = $Redis->get("wenshi_12");
//                if(!$res && $arr = array_diff($data1,$res)  ){
//                    $Redis->set("wenshi_12",$data1);
//                    $sql = "update "
//                    foreach ($arr as $k => $v){
//                        $sql = " "
//                    }
//                    self::$db->query("");
//                }


            }
            // type == 3 定时上传数据
            if ($data1['type'] == 3) {
				
                // 实时数据
                $Redis->set($data1['gateway_id'],json_encode($data1));
                // 启用redis 比较时间 10分钟放一次队列
                $interval_time = $Redis->get('nyd_interval_time');
                
                if(!$interval_time){
                    var_dump('首次进入redis,并添加队列');
                    //添加到队列
                    $queueds = new Queueds("first");
                    $queueds->send($data1);

                    $interval_time = time();
                    $Redis->set('nyd_interval_time',$interval_time);
                }else{
                    // 时间比较
                    $time_sec = time() - $interval_time;
                    var_dump('时间间隔----'.$time_sec);

                    if($time_sec >= 600){
                        var_dump('插入队列');

                        //添加到队列
                        $queueds = new Queueds("first");
                        $queueds->send($data1);

                        $interval_time = time();
                        $Redis->set('nyd_interval_time',$interval_time);
                    }
                }
               
            }

            // type == 'ping'  心跳检测 不做处理
            if ($data1['type'] == 'ping') {
            	
            	Gateway::sendToClientId($client_id,json_encode($data1));
            }
        }
    }

    /**
     * 当用户断开连接时触发
     * @param int $client_id 连接id
     */
    public static function onClose($client_id)
    {
        // 向所有人发送
        //        GateWay::sendToAll("$client_id logout\r\n");
        var_dump($client_id . "logout");
    }
}
